package com.viettel.pon.Tabs;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.viettel.pon.R;
import com.viettel.pon.DAO.AuthenDAO;
import com.viettel.pon.DAO.SyncPonDAO;
import com.viettel.pon.common.CheckConnect;
import com.viettel.pon.common.DataBaseHelper;
import com.viettel.pon.common.DialogCommon;
import com.viettel.pon.common.GlobalClass;
import com.viettel.pon.common.RequestMethod;
import com.viettel.pon.common.RestClient;
import com.viettel.pon.common.Spin;
import com.viettel.pon.config.Config;
import com.viettel.pon.form.InfomationForm;
import com.viettel.pon.form.PoleForm;
import com.viettel.pon.form.ResultLoginForm;
import com.viettel.pon.httpclient.HttpBasicClientHelper;
import com.viettel.pon.httpclient.MyJsonHttpResponseHandler;

public class SyncActivity extends Fragment {
	private Logger mLog;
	private Button btnSyncData;
	private ProgressDialog pDialog;
	Button sign_in_button;
	EditText password;
	EditText username;
	DataBaseHelper db;
	DialogCommon _dlg;
	SyncPonDAO _sync = new SyncPonDAO();
	String resultSyncPoles = "";
	GlobalClass _glb;
	private Context _context;
	private int typeSync = 0;
	List<PoleForm> lstPoles = new ArrayList<PoleForm>();
	AuthenDAO _authen = new AuthenDAO();
	ResultLoginForm resultForm = new ResultLoginForm();
	private String mUserName;
	private String mPassword;
	Boolean isConnectionExist = false;
	// Ã„ï¿½Ã¡Â»â€˜i tÃ†Â°Ã¡Â»Â£ng kiÃ¡Â»Æ’m tra kÃ¡ÂºÂ¿t nÃ¡Â»â€˜i internet
	CheckConnect _checkConnect;
	private PopupWindow popupWindow;
	Dialog dialog;
	Spinner spnChooseDept;
	ArrayAdapter<com.viettel.pon.common.Spin> dataAdapterProgress = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mLog = Logger.getLogger(SyncActivity.class);
		View rootView = inflater.inflate(R.layout.activity_sync, container,
				false);
		btnSyncData = (Button) rootView.findViewById(R.id.btnSyncData);
		db = new DataBaseHelper(getActivity().getApplicationContext());
		_dlg = new DialogCommon(getActivity());
		_context = getActivity().getApplicationContext();
		_glb = (GlobalClass) getActivity().getApplicationContext();
		_checkConnect = new CheckConnect(_context);
		btnSyncData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Show popup Login");
				showPopup();
				// String URL =
				// Config.URL_WS+"sync/startPoles";
				// new SyncPoles().execute(URL);
				// dialog.dismiss();
			}
		});
		return rootView;
	}

	/*
	 * Dong bo du lieu cot
	 */
	class SyncPoles extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ cá»™t thÃ nh cÃ´ng";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
			
				Log.i("Hungnd40", "start");
				mLog.info("Sync poles start");
				//RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();
				List<InfomationForm> listPoles = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listPoles.add(ssid);
				
				//listPoles.addAll(db.getPoleNotInserted());
//				for(int i=0;i<200;i++){
//					ssid = new InfomationForm();				
//					ssid.setId(i);
//					ssid.setCol_code(String.valueOf(i));
//					ssid.setLatitude("10.6");
//					ssid.setLongtitude("10.8");
//					ssid.setCol_type(1);
//					ssid.setOwner(1);
//					ssid.setNum_people(0);
//					ssid.setNeworold(1);
//					ssid.setNote(String.valueOf(i));
//					ssid.setUsername("duytv5");					
//					listPoles.add(ssid);
//					
//					Log.i("DATA", ""+ i);
//				}
				
				Log.i("Hungnd40", "pre get data");
			
				listPoles.addAll(db.getPoleNotInserted());
				
				Log.i("Hungnd40", "so cot  "+listPoles.size());
				
				System.out.println("So luong cot: "+listPoles.size());

				byte[] encodedBytes = Base64.encodeBase64(gson
						.toJson(listPoles).getBytes());
				
				//syncPole(encodedBytes);
				
				//sendData("/sdcard/abc.jpg", Config.URL_WS_VSMART_TEST);
			
				
				
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se = new StringEntity(new String(encodedBytes,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				httpost.setHeader("Accept", "application/json");
				httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				// String httpResponse;
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					if(Content.contains("OK")) db.updateCommitedStatus("POLES_LIST");
				}
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync poles fail", e);
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();

					} else {
						JSONObject json;
						try {
							json = new JSONObject(Content);
							if (json.has("resultPole")
									&& json.getString("resultPole")
											.equals("OK")) {

								db.updateInsertedData("POLES_LIST");
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ khÃ´ng thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync poles end");
							String URL1 = Config.URL_WS + "sync/startHouse";
							new SyncHouse().execute(URL1);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync poles get result fail", e);
						}
					}

				}
			});
		

		}

	}

	/*
	 * Sync house
	 */

	class SyncHouse extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ nhÃ  thÃ nh cÃ´ng";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
				mLog.info("Sync house start");
				RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();
				List<InfomationForm> listHouse = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listHouse.add(ssid);
				listHouse.addAll(db.getHouseNotInserted());
				// List<InfomationForm> listHouse = db.getAllHouse();
				byte[] encodedBytes = Base64.encodeBase64(gson
						.toJson(listHouse).getBytes());
				client.AddHeader("houseList", gson.toJson(listHouse));
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se = new StringEntity(new String(encodedBytes,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				httpost.setHeader("Accept", "application/json");
				httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				// String httpResponse;
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					
					if(Content.contains("OK")) db.updateCommitedStatus("HOUSE_LIST");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync house fail", e);
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();
					} else {
						try {
							JSONObject json;
							json = new JSONObject(Content);

							if (json.has("resultHouse")
									&& json.getString("resultHouse").equals(
											"OK")) {
								typeSync = 3;
								resultSucc += "NhÃƒÂ , ";
								db.updateInsertedData("HOUSE_LIST");
								Toast.makeText(_context,
										"Ä�á»“ng bá»™ nhÃ  thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ nhÃ  khÃ´ng thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync house end");
							String URL2 = Config.URL_WS + "sync/startPlace";
							new SyncPlace().execute(URL2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync house get result fail", e);
						}
					}
				}
			});
		}
	}

	/*
	 * Sync place
	 */

	class SyncPlace extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ nhÃ  thÃ nh cÃ´ng";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
				mLog.info("Sync Place start");
				RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();

				List<InfomationForm> listPlace = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listPlace.add(ssid);
				listPlace.addAll(db.getPlaceNotInserted());

				// List<InfomationForm> listPlace = db.getAllPlace();
				byte[] encodedBytes = Base64.encodeBase64(gson
						.toJson(listPlace).getBytes());
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se = new StringEntity(new String(encodedBytes,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				httpost.setHeader("Accept", "application/json");
				httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					
					if(Content.contains("OK")) db.updateCommitedStatus("PLACE_LIST");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync place fail", e);
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();
					} else {
						JSONObject json;
						try {
							json = new JSONObject(Content);
							if (json.has("resultPlace")
									&& json.getString("resultPlace").equals(
											"OK")) {
								db.updateInsertedData("PLACE_LIST");
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ Ä‘á»‹a danh thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ Ä‘á»‹a danh khÃ´ng thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync place end");
							String URL3 = Config.URL_WS + "sync/startRoad";
							new SyncRoad().execute(URL3);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync place get result fail", e);
						}
					}

				}
			});

		}

	}

	/*
	 * Sync Road
	 */

	class SyncRoad extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ Ä‘Æ°á»�ng thÃ nh cÃ´ng.";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
				mLog.info("Sync Road start");

				RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();
				List<InfomationForm> listTimeStop = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listTimeStop.add(ssid);
				listTimeStop.addAll(db.getRoadNotInserted());
				// List<InfomationForm> listTimeStop = db.getAllTimeStop();
				List<InfomationForm> listPosition = db.getAllPositionNotInserted();
				String dataPost = gson.toJson(listTimeStop) + "-----"
						+ gson.toJson(listPosition);
				byte[] encodedBytes = Base64.encodeBase64(gson.toJson(
						listTimeStop).getBytes());
				byte[] encodedBytes1 = Base64.encodeBase64(dataPost.getBytes());
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se1 = new StringEntity(new String(encodedBytes1,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se1);
				// StringEntity se = new StringEntity(new String(encodedBytes,
				// "UTF-8"));
				// httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				// httpost.setHeader("timeList", new String(encodedBytes,
				// "UTF-8"));
				// httpost.setHeader("Accept", "application/json");
				// httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					
					if(Content.contains("OK")) db.updateCommitedStatus("LIST_TIME_STOP");
					if(Content.contains("OK")) db.updateCommitedStatus("POSITION_LIST");
				}
				//
				// try {
				// client.Execute(RequestMethod.POST);
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				// Content = client.getResponse();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync road fail", e);
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();
					} else {
						JSONObject json;
						try {
							json = new JSONObject(Content);
							if (json.has("resultPosition")
									&& json.getString("resultPosition").equals(
											"OK")) {
								db.updateInsertedData("LIST_TIME_STOP");
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ khÃ´ng thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync Road end");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync road get result fail", e);
						}
					}

				}
			});

		}

	}

	/*
	 * show man hinh dang nhap
	 */

	private void showPopup() {
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);

		View popupView = layoutInflater.inflate(R.layout.activity_login_sync,
				null);
		sign_in_button = (Button) popupView.findViewById(R.id.sign_in_button);
		Button btnCancel = (Button) popupView.findViewById(R.id.cancel_button);
		username = (EditText) popupView.findViewById(R.id.username);
		password = (EditText) popupView.findViewById(R.id.password);
		popupWindow = new PopupWindow(popupView,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.update();

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
		});

		sign_in_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Login start");
				isConnectionExist = _checkConnect.checkData();
				mUserName = username.getText().toString();
				mPassword = password.getText().toString();
				if (mUserName.equals("") || mPassword.equals("")) {
					AlertDialog myErrorDialog = createDialogError("Báº¡n pháº£i nháº­p user vÃ  pass");
					myErrorDialog.show();
				} else {

					if (isConnectionExist) {
						mLog.info("Login end success");
						AsyncCallWS task = new AsyncCallWS();
						task.execute();

					} else {
						mLog.info("Login end fail");
						AlertDialog myErrorDialog = createDialogError("Vui lÃ²ng kiá»ƒm tra láº¡i káº¿t ná»‘i máº¡ng");
						myErrorDialog.show();
					}
				}
			}
		});
	}

	private AlertDialog createDialogError(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("ThÃ´ng bÃ¡o");
		builder.setMessage(msg);
		builder.setCancelable(false);
		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				username.setText("");
				password.setText("");
				username.requestFocus();
			}
		});
		AlertDialog dialog = builder.create();
		return dialog;
	}

	private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
		private String Content;
		private String Error = null;

		@Override
		protected Void doInBackground(Void... params) {
			try {
				// Send POST data request
				Content = getRespose(Config.URL_WS + "sync/authen");
			} catch (Exception ex) {
				Error = ex.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			pDialog.dismiss();
			if (Error != null) {
				Toast.makeText(_context, Error, Toast.LENGTH_SHORT).show();

			} else {
				try {
					if (Content.equals("") || Content == null
							|| Content.equals("-1")) {
						Toast.makeText(_context,
								"Ä�Äƒng nháº­p khÃ´ng thÃ nh cÃ´ng",
								Toast.LENGTH_SHORT).show();
					} else {
						JSONObject jsonResponse;
						jsonResponse = new JSONObject(Content);
						String errorCode = "";
						String sessionId = "";
						if (jsonResponse.has("datauser")) {
							JSONObject datauser = jsonResponse
									.getJSONObject("datauser");
							errorCode = datauser.has("errorCode") != true ? ""
									: datauser.getString("errorCode");
							sessionId = datauser.has("sessionId") != true ? ""
									: datauser.getString("sessionId");
						}
						if (jsonResponse.has("lstDept")) {
							JSONArray lstCatWork = jsonResponse
									.getJSONArray("lstDept");
							List<com.viettel.pon.common.Spin> lableProgress = listCatWork(lstCatWork);
							dataAdapterProgress = new ArrayAdapter<com.viettel.pon.common.Spin>(
									getActivity(), R.layout.spinner_item,
									lableProgress);
							dataAdapterProgress
									.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

						}

						if (!errorCode.equals("OK")) {
							_glb.setSid(sessionId);
							Toast.makeText(_context,
									"Ä�Äƒng nháº­p khÃ´ng thÃ nh cÃ´ng",
									Toast.LENGTH_SHORT).show();
							// Intent intent = new Intent();
							// intent.setClass(_context, MainActivity.class);
							// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							// _context.startActivity(intent);
						} else {
							// AlertDialog myErrorDialog =
							// createDialogError("Sai tÃƒÂªn Ã„â€˜Ã„Æ’ng nhÃ¡ÂºÂ­p hoÃ¡ÂºÂ·c password");
							// myErrorDialog.show();
							_glb.setSid(sessionId);
							// _glb.setLocationId(locationId);
							Toast.makeText(_context, "login ok",
									Toast.LENGTH_SHORT).show();
							showPopupChooseDept();

							popupWindow.dismiss();

							pDialog.dismiss();
						}
					}

				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		}

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�Äƒng nháº­p");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

	}

	public String getRespose(String url) {
		String response = "";
		try {

			RestClient client = new RestClient(url);
			byte[] encodedUser = Base64.encodeBase64(username.getText()
					.toString().getBytes());
			byte[] encodedPass = Base64.encodeBase64(password.getText()
					.toString().getBytes());
			client.AddHeader("username", new String(encodedUser, "UTF-8"));
			client.AddHeader("password", new String(encodedPass, "UTF-8"));
			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {
				e.printStackTrace();

			}
			response = client.getResponse();

		} catch (Exception e) {

			System.out.println(e.getMessage());
		}
		return response;
	}

	private void showPopupChooseDept() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(dialog.getWindow().FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.activity_choose_dept_sync);

		Button sign_in_button = (Button) dialog
				.findViewById(R.id.sign_in_button);
		spnChooseDept = (Spinner) dialog.findViewById(R.id.spnChooseDept);
		if (dataAdapterProgress != null) {
			spnChooseDept.setAdapter(dataAdapterProgress);
		}

		sign_in_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				if (locotion != null) {
					dlgConfirmInsertCol().show();
				} else {
//					Toast.makeText(_context,
//							"Báº¡n cÃ³ muá»‘n Ä‘á»“ng bá»™",
//							Toast.LENGTH_SHORT).show();
				}
			}
		});
		dialog.show();
	}

	private List<com.viettel.pon.common.Spin> listCatWork(JSONArray listCatWork) {
		List<com.viettel.pon.common.Spin> labels = new ArrayList<com.viettel.pon.common.Spin>();
		try {
			for (int i = 0; i < listCatWork.length(); i++) {
				JSONObject c = listCatWork.getJSONObject(i);
				labels.add(new com.viettel.pon.common.Spin(c
						.getString("locationId"), c.getString("locationName")));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return labels;
	}

	public AlertDialog dlgConfirmInsertCol() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("ThÃ´ng bÃ¡o");
		Spin locotion = (Spin) spnChooseDept.getSelectedItem();
		if (locotion != null) {
			builder.setMessage("Báº¡n cÃ³ muá»‘n Ä‘á»“ng bá»™"
					+ locotion.getValue());
		}
		builder.setCancelable(false);
		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(_context, "Dang dong bo du lieu",
						Toast.LENGTH_SHORT).show();
				String URL = Config.URL_WS + "sync/startPoles";
				new SyncPoles().execute(URL);
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mLog.info("Sync Cancel");
					}
				});
		AlertDialog dialog = builder.create();
		return dialog;
	}
	
	
	// doan sync du lieu.
	void syncPole(byte[] listPole){
		RequestParams params = new RequestParams();
		params.put("listPoles", new ByteArrayInputStream(listPole), "listPoles");
		
		AsyncHttpClient client = new AsyncHttpClient();
		client.setTimeout(120000);
		client.post(Config.URL_WS_VSMART, params, new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(int statusCode, Throwable error) {
				//super.onFailure(statusCode, error);
				Log.i("DATA", error.toString());
			}

			@Override
			public void onSuccess(int statusCode, JSONObject re) {
				try {
					Log.i("DATA", re.toString());
					if (statusCode == 200){
						Log.i("DATA", "Tranfer thanh cong");
					} else {
						Log.i("DATA", "Tranfer thatbai");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
		});
	}
	
	void uploadImage(byte[] bbnt, byte[] bbbgtb) {
		
		RequestParams params = new RequestParams();
		params.put("userAssignId", String.valueOf(1));
		params.put("taskId", String.valueOf(1));
		params.put("BBNT", new ByteArrayInputStream(bbnt), "bbnt.jpg");
		params.put("BBBGTB", new ByteArrayInputStream(bbbgtb), "bbbgtb.jpg");

		AsyncHttpClient client = new AsyncHttpClient();
		client.post(HttpBasicClientHelper.BASE_URL , params,
			new MyJsonHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, JSONObject re) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onFailure(int statusCode, Throwable error) {
					// TODO Auto-generated method stub
					
				}

			    
			});
	    }
	
	private byte[] convertFromFile(String source) {
		File f = new File(source);
		InputStream in = null;
		try {
			in = new FileInputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		byte[] buff = new byte[8000];

		int bytesRead = 0;

		ByteArrayOutputStream bao = new ByteArrayOutputStream();

		try {
			while ((bytesRead = in.read(buff)) != -1) {
			bao.write(buff, 0, bytesRead);
			}
			bao.flush();
			if (null != in)
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	}

		byte[] data = bao.toByteArray();

		Log.d("Tuan", this.getClass().getSimpleName() + " convertFromFile source:" + source + " data:" + data);

		// ByteArrayOutputStream stream = new ByteArrayOutputStream();
		// byteArray = stream.toByteArray();

		return data;
    }
	
	

	private void sendData(String path, String url){
		
		HttpClient httpclient = new DefaultHttpClient();
		String Url = url + "workMaintainController/onUpdateComplete";
		HttpPost httppost = new HttpPost(Url);
		try {
			MultipartEntity reqEntity = new MultipartEntity();
			int i = 0;
			FileBody bin = new FileBody(new File(path));
			StringBody comment = new StringBody("Upload Image");
			String partName = "fileup" + String.valueOf(i);
			reqEntity.addPart(partName, bin);
			// set gia tri update cong viec

			httppost.setEntity(reqEntity);
			httppost.addHeader("workingId", "1");
			
			httppost.addHeader("sid", "1");
			httppost.addHeader("userName", "duytv5");

			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost,
					responseHandler);
			Log.i("QLCTKT", "responseBody : " + responseBody);
			System.out.println("responseBody : " + responseBody);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

}
/*package com.viettel.pon.Tabs;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.viettel.pon.R;
import com.viettel.pon.DAO.AuthenDAO;
import com.viettel.pon.DAO.SyncPonDAO;
import com.viettel.pon.common.CheckConnect;
import com.viettel.pon.common.DataBaseHelper;
import com.viettel.pon.common.DialogCommon;
import com.viettel.pon.common.GlobalClass;
import com.viettel.pon.common.RequestMethod;
import com.viettel.pon.common.RestClient;
import com.viettel.pon.common.Spin;
import com.viettel.pon.config.Config;
import com.viettel.pon.form.InfomationForm;
import com.viettel.pon.form.PoleForm;
import com.viettel.pon.form.ResultLoginForm;
import com.viettel.pon.httpclient.HttpBasicClientHelper;
import com.viettel.pon.httpclient.MyJsonHttpResponseHandler;

public class SyncActivity extends Fragment {
	private Logger mLog;
	private Button btnSyncData;
	private ProgressDialog pDialog;
	Button sign_in_button;
	EditText password;
	EditText username;
	DataBaseHelper db;
	DialogCommon _dlg;
	SyncPonDAO _sync = new SyncPonDAO();
	String resultSyncPoles = "";
	GlobalClass _glb;
	private Context _context;
	private int typeSync = 0;
	List<PoleForm> lstPoles = new ArrayList<PoleForm>();
	AuthenDAO _authen = new AuthenDAO();
	ResultLoginForm resultForm = new ResultLoginForm();
	private String mUserName;
	private String mPassword;
	Boolean isConnectionExist = false;
	// Ã„ï¿½Ã¡Â»â€˜i tÃ†Â°Ã¡Â»Â£ng kiÃ¡Â»Æ’m tra kÃ¡ÂºÂ¿t nÃ¡Â»â€˜i internet
	CheckConnect _checkConnect;
	private PopupWindow popupWindow;
	Dialog dialog;
	Spinner spnChooseDept;
	ArrayAdapter<com.viettel.pon.common.Spin> dataAdapterProgress = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mLog = Logger.getLogger(SyncActivity.class);
		View rootView = inflater.inflate(R.layout.activity_sync, container,
				false);
		btnSyncData = (Button) rootView.findViewById(R.id.btnSyncData);
		db = new DataBaseHelper(getActivity().getApplicationContext());
		_dlg = new DialogCommon(getActivity());
		_context = getActivity().getApplicationContext();
		_glb = (GlobalClass) getActivity().getApplicationContext();
		_checkConnect = new CheckConnect(_context);
		btnSyncData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Show popup Login");
				showPopup();
				// String URL =
				// Config.URL_WS+"sync/startPoles";
				// new SyncPoles().execute(URL);
				// dialog.dismiss();
			}
		});
		return rootView;
	}

	
	 * Dong bo du lieu cot
	 
	class SyncPoles extends AsyncTask<String, String, String> {
		*//**
		 * Before starting background thread Show Progress Dialog
		 * *//*
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ cá»™t thÃ nh cÃ´ng";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		*//**
		 * getting All products from url
		 * *//*
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
			
				Log.i("Hungnd40", "start");
				mLog.info("Sync poles start");
				//RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();
				List<InfomationForm> listPoles = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listPoles.add(ssid);
				
				//listPoles.addAll(db.getPoleNotInserted());
//				for(int i=0;i<200;i++){
//					ssid = new InfomationForm();				
//					ssid.setId(i);
//					ssid.setCol_code(String.valueOf(i));
//					ssid.setLatitude("10.6");
//					ssid.setLongtitude("10.8");
//					ssid.setCol_type(1);
//					ssid.setOwner(1);
//					ssid.setNum_people(0);
//					ssid.setNeworold(1);
//					ssid.setNote(String.valueOf(i));
//					ssid.setUsername("duytv5");					
//					listPoles.add(ssid);
//					
//					Log.i("DATA", ""+ i);
//				}
				
				Log.i("Hungnd40", "pre get data");
			
				listPoles.addAll(db.getPoleNotInserted());
				
				Log.i("Hungnd40", "so cot  "+listPoles.size());
				
				System.out.println("So luong cot: "+listPoles.size());

				byte[] encodedBytes = Base64.encodeBase64(gson
						.toJson(listPoles).getBytes());
				
				//syncPole(encodedBytes);
				
				//sendData("/sdcard/abc.jpg", Config.URL_WS_VSMART_TEST);
			
				
				
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se = new StringEntity(new String(encodedBytes,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				httpost.setHeader("Accept", "application/json");
				httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				// String httpResponse;
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					if(Content.contains("OK")) db.updateCommitedStatus("POLES_LIST");
				}
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync poles fail", e);
			}
			return null;
		}

		*//**
		 * After completing background task Dismiss the progress dialog
		 * **//*
		@Override
		protected void onPostExecute(String file_url) {
			
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();

					} else {
						JSONObject json;
						try {
							json = new JSONObject(Content);
							if (json.has("resultPole")
									&& json.getString("resultPole")
											.equals("OK")) {

								db.updateInsertedData("POLES_LIST");
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ khÃ´ng thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync poles end");
							String URL1 = Config.URL_WS + "sync/startHouse";
							new SyncHouse().execute(URL1);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync poles get result fail", e);
						}
					}

				}
			});
		

		}

	}

	
	 * Sync house
	 

	class SyncHouse extends AsyncTask<String, String, String> {
		*//**
		 * Before starting background thread Show Progress Dialog
		 * *//*
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ nhÃ  thÃ nh cÃ´ng";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		*//**
		 * getting All products from url
		 * *//*
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
				mLog.info("Sync house start");
				RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();
				List<InfomationForm> listHouse = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listHouse.add(ssid);
				listHouse.addAll(db.getHouseNotInserted());
				// List<InfomationForm> listHouse = db.getAllHouse();
				byte[] encodedBytes = Base64.encodeBase64(gson
						.toJson(listHouse).getBytes());
				client.AddHeader("houseList", gson.toJson(listHouse));
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se = new StringEntity(new String(encodedBytes,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				httpost.setHeader("Accept", "application/json");
				httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				// String httpResponse;
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					
					if(Content.contains("OK")) db.updateCommitedStatus("HOUSE_LIST");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync house fail", e);
			}
			return null;
		}

		*//**
		 * After completing background task Dismiss the progress dialog
		 * **//*
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();
					} else {
						try {
							JSONObject json;
							json = new JSONObject(Content);

							if (json.has("resultHouse")
									&& json.getString("resultHouse").equals(
											"OK")) {
								typeSync = 3;
								resultSucc += "NhÃƒÂ , ";
								db.updateInsertedData("HOUSE_LIST");
								Toast.makeText(_context,
										"Ä�á»“ng bá»™ nhÃ  thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ nhÃ  khÃ´ng thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync house end");
							String URL2 = Config.URL_WS + "sync/startPlace";
							new SyncPlace().execute(URL2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync house get result fail", e);
						}
					}
				}
			});
		}
	}

	
	 * Sync place
	 

	class SyncPlace extends AsyncTask<String, String, String> {
		*//**
		 * Before starting background thread Show Progress Dialog
		 * *//*
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ nhÃ  thÃ nh cÃ´ng";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		*//**
		 * getting All products from url
		 * *//*
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
				mLog.info("Sync Place start");
				RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();

				List<InfomationForm> listPlace = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listPlace.add(ssid);
				listPlace.addAll(db.getPlaceNotInserted());

				// List<InfomationForm> listPlace = db.getAllPlace();
				byte[] encodedBytes = Base64.encodeBase64(gson
						.toJson(listPlace).getBytes());
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se = new StringEntity(new String(encodedBytes,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				httpost.setHeader("Accept", "application/json");
				httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					
					if(Content.contains("OK")) db.updateCommitedStatus("PLACE_LIST");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync place fail", e);
			}
			return null;
		}

		*//**
		 * After completing background task Dismiss the progress dialog
		 * **//*
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();
					} else {
						JSONObject json;
						try {
							json = new JSONObject(Content);
							if (json.has("resultPlace")
									&& json.getString("resultPlace").equals(
											"OK")) {
								db.updateInsertedData("PLACE_LIST");
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ Ä‘á»‹a danh thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ Ä‘á»‹a danh khÃ´ng thÃ nh cÃ´ng.",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync place end");
							String URL3 = Config.URL_WS + "sync/startRoad";
							new SyncRoad().execute(URL3);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync place get result fail", e);
						}
					}

				}
			});

		}

	}

	
	 * Sync Road
	 

	class SyncRoad extends AsyncTask<String, String, String> {
		*//**
		 * Before starting background thread Show Progress Dialog
		 * *//*
		private String Content;
		String resultSucc = "Ä�á»“ng bá»™ Ä‘Æ°á»�ng thÃ nh cÃ´ng.";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�ang Ä‘á»“ng bá»™ dá»¯ liá»‡u");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		*//**
		 * getting All products from url
		 * *//*
		@Override
		protected String doInBackground(String... urls) {
			// Building Parameters
			try {
				mLog.info("Sync Road start");

				RestClient client = new RestClient(urls[0]);
				Gson gson = new Gson();
				List<InfomationForm> listTimeStop = new ArrayList<InfomationForm>();
				InfomationForm ssid = new InfomationForm();
				ssid.setSessionId(_glb.getSid());
				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				ssid.setLocationId(locotion.getId());
				listTimeStop.add(ssid);
				listTimeStop.addAll(db.getRoadNotInserted());
				// List<InfomationForm> listTimeStop = db.getAllTimeStop();
				List<InfomationForm> listPosition = db.getAllPositionNotInserted();
				String dataPost = gson.toJson(listTimeStop) + "-----"
						+ gson.toJson(listPosition);
				byte[] encodedBytes = Base64.encodeBase64(gson.toJson(
						listTimeStop).getBytes());
				byte[] encodedBytes1 = Base64.encodeBase64(dataPost.getBytes());
				// instantiates httpclient to make request
				DefaultHttpClient httpclient = new DefaultHttpClient();

				// url with the post data
				HttpPost httpost = new HttpPost(urls[0]);

				// passes the results to a string builder/entity
				StringEntity se1 = new StringEntity(new String(encodedBytes1,
						"UTF-8"));
				// sets the post request as the resulting string
				httpost.setEntity(se1);
				// StringEntity se = new StringEntity(new String(encodedBytes,
				// "UTF-8"));
				// httpost.setEntity(se);
				// sets a request header so the page receving the request
				// will know what to do with it
				// httpost.setHeader("timeList", new String(encodedBytes,
				// "UTF-8"));
				// httpost.setHeader("Accept", "application/json");
				// httpost.setHeader("Content-type", "application/json");

				// Handles what is returned from the page
				ResponseHandler responseHandler = new BasicResponseHandler();
				HttpResponse httpResponse;
				HttpParams parameter = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(parameter,
						Config.HTTP_TIME_OUT);
				HttpConnectionParams.setSoTimeout(parameter,
						Config.HTTP_TIME_OUT);
				httpost.setParams(parameter);
				httpResponse = httpclient.execute(httpost);
				int responseCode;
				String message;
				responseCode = httpResponse.getStatusLine().getStatusCode();

				if (responseCode == 200) {
					HttpEntity entity = httpResponse.getEntity();
					Content = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
					
					if(Content.contains("OK")) db.updateCommitedStatus("LIST_TIME_STOP");
					if(Content.contains("OK")) db.updateCommitedStatus("POSITION_LIST");
				}
				//
				// try {
				// client.Execute(RequestMethod.POST);
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				// Content = client.getResponse();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				mLog.error("Sync road fail", e);
			}
			return null;
		}

		*//**
		 * After completing background task Dismiss the progress dialog
		 * **//*
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (Content == null || Content.equals("")
							|| Content.equals("-1")) {
						mLog.info("Connect error");
						AlertDialog myErrorDialog = _dlg
								.createDialogErrorNotReturn("Lá»—i káº¿t ná»‘i");
						myErrorDialog.show();
					} else {
						JSONObject json;
						try {
							json = new JSONObject(Content);
							if (json.has("resultPosition")
									&& json.getString("resultPosition").equals(
											"OK")) {
								db.updateInsertedData("LIST_TIME_STOP");
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(
										_context,
										"Ä�á»“ng bá»™ khÃ´ng thÃ nh cÃ´ng",
										Toast.LENGTH_SHORT).show();
							}
							mLog.info("Sync Road end");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							mLog.error("Sync road get result fail", e);
						}
					}

				}
			});

		}

	}

	
	 * show man hinh dang nhap
	 

	private void showPopup() {
		LayoutInflater layoutInflater = (LayoutInflater) getActivity()
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);

		View popupView = layoutInflater.inflate(R.layout.activity_login_sync,
				null);
		sign_in_button = (Button) popupView.findViewById(R.id.sign_in_button);
		Button btnCancel = (Button) popupView.findViewById(R.id.cancel_button);
		username = (EditText) popupView.findViewById(R.id.username);
		password = (EditText) popupView.findViewById(R.id.password);
		popupWindow = new PopupWindow(popupView,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.update();

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupWindow.dismiss();
			}
		});

		sign_in_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mLog.info("Login start");
				isConnectionExist = _checkConnect.checkData();
				mUserName = username.getText().toString();
				mPassword = password.getText().toString();
				if (mUserName.equals("") || mPassword.equals("")) {
					AlertDialog myErrorDialog = createDialogError("Báº¡n pháº£i nháº­p user vÃ  pass");
					myErrorDialog.show();
				} else {

					if (isConnectionExist) {
						mLog.info("Login end success");
						AsyncCallWS task = new AsyncCallWS();
						task.execute();

					} else {
						mLog.info("Login end fail");
						AlertDialog myErrorDialog = createDialogError("Vui lÃ²ng kiá»ƒm tra láº¡i káº¿t ná»‘i máº¡ng");
						myErrorDialog.show();
					}
				}
			}
		});
	}

	private AlertDialog createDialogError(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("ThÃ´ng bÃ¡o");
		builder.setMessage(msg);
		builder.setCancelable(false);
		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				username.setText("");
				password.setText("");
				username.requestFocus();
			}
		});
		AlertDialog dialog = builder.create();
		return dialog;
	}

	private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
		private String Content;
		private String Error = null;

		@Override
		protected Void doInBackground(Void... params) {
			try {
				// Send POST data request
				Content = getRespose(Config.URL_WS + "sync/authen");
			} catch (Exception ex) {
				Error = ex.getMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			pDialog.dismiss();
			if (Error != null) {
				Toast.makeText(_context, Error, Toast.LENGTH_SHORT).show();

			} else {
				try {
					if (Content.equals("") || Content == null
							|| Content.equals("-1")) {
						Toast.makeText(_context,
								"Ä�Äƒng nháº­p khÃ´ng thÃ nh cÃ´ng",
								Toast.LENGTH_SHORT).show();
					} else {
						JSONObject jsonResponse;
						jsonResponse = new JSONObject(Content);
						String errorCode = "";
						String sessionId = "";
						if (jsonResponse.has("datauser")) {
							JSONObject datauser = jsonResponse
									.getJSONObject("datauser");
							errorCode = datauser.has("errorCode") != true ? ""
									: datauser.getString("errorCode");
							sessionId = datauser.has("sessionId") != true ? ""
									: datauser.getString("sessionId");
						}
						if (jsonResponse.has("lstDept")) {
							JSONArray lstCatWork = jsonResponse
									.getJSONArray("lstDept");
							List<com.viettel.pon.common.Spin> lableProgress = listCatWork(lstCatWork);
							dataAdapterProgress = new ArrayAdapter<com.viettel.pon.common.Spin>(
									getActivity(), R.layout.spinner_item,
									lableProgress);
							dataAdapterProgress
									.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

						}

						if (!errorCode.equals("OK")) {
							_glb.setSid(sessionId);
							Toast.makeText(_context,
									"Ä�Äƒng nháº­p khÃ´ng thÃ nh cÃ´ng",
									Toast.LENGTH_SHORT).show();
							// Intent intent = new Intent();
							// intent.setClass(_context, MainActivity.class);
							// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							// _context.startActivity(intent);
						} else {
							// AlertDialog myErrorDialog =
							// createDialogError("Sai tÃƒÂªn Ã„â€˜Ã„Æ’ng nhÃ¡ÂºÂ­p hoÃ¡ÂºÂ·c password");
							// myErrorDialog.show();
							_glb.setSid(sessionId);
							// _glb.setLocationId(locationId);
							Toast.makeText(_context, "login ok",
									Toast.LENGTH_SHORT).show();
							showPopupChooseDept();

							popupWindow.dismiss();

							pDialog.dismiss();
						}
					}

				} catch (Exception e) {

					e.printStackTrace();
				}
			}
		}

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Ä�Äƒng nháº­p");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

	}

	public String getRespose(String url) {
		String response = "";
		try {

			RestClient client = new RestClient(url);
			byte[] encodedUser = Base64.encodeBase64(username.getText()
					.toString().getBytes());
			byte[] encodedPass = Base64.encodeBase64(password.getText()
					.toString().getBytes());
			client.AddHeader("username", new String(encodedUser, "UTF-8"));
			client.AddHeader("password", new String(encodedPass, "UTF-8"));
			try {
				client.Execute(RequestMethod.POST);
			} catch (Exception e) {
				e.printStackTrace();

			}
			response = client.getResponse();

		} catch (Exception e) {

			System.out.println(e.getMessage());
		}
		return response;
	}

	private void showPopupChooseDept() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(dialog.getWindow().FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.activity_choose_dept_sync);

		Button sign_in_button = (Button) dialog
				.findViewById(R.id.sign_in_button);
		spnChooseDept = (Spinner) dialog.findViewById(R.id.spnChooseDept);
		if (dataAdapterProgress != null) {
			spnChooseDept.setAdapter(dataAdapterProgress);
		}

		sign_in_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Spin locotion = (Spin) spnChooseDept.getSelectedItem();
				if (locotion != null) {
					dlgConfirmInsertCol().show();
				} else {
//					Toast.makeText(_context,
//							"Báº¡n cÃ³ muá»‘n Ä‘á»“ng bá»™",
//							Toast.LENGTH_SHORT).show();
				}
			}
		});
		dialog.show();
	}

	private List<com.viettel.pon.common.Spin> listCatWork(JSONArray listCatWork) {
		List<com.viettel.pon.common.Spin> labels = new ArrayList<com.viettel.pon.common.Spin>();
		try {
			for (int i = 0; i < listCatWork.length(); i++) {
				JSONObject c = listCatWork.getJSONObject(i);
				labels.add(new com.viettel.pon.common.Spin(c
						.getString("locationId"), c.getString("locationName")));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return labels;
	}

	public AlertDialog dlgConfirmInsertCol() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("ThÃ´ng bÃ¡o");
		Spin locotion = (Spin) spnChooseDept.getSelectedItem();
		if (locotion != null) {
			builder.setMessage("Báº¡n cÃ³ muá»‘n Ä‘á»“ng bá»™"
					+ locotion.getValue());
		}
		builder.setCancelable(false);
		builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(_context, "Dang dong bo du lieu",
						Toast.LENGTH_SHORT).show();
				String URL = Config.URL_WS + "sync/startPoles";
				new SyncPoles().execute(URL);
				dialog.dismiss();
			}
		});
		builder.setPositiveButton("Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						mLog.info("Sync Cancel");
					}
				});
		AlertDialog dialog = builder.create();
		return dialog;
	}
	
	
	// doan sync du lieu.
	void syncPole(byte[] listPole){
		RequestParams params = new RequestParams();
		params.put("listPoles", new ByteArrayInputStream(listPole), "listPoles");
		
		AsyncHttpClient client = new AsyncHttpClient();
		client.setTimeout(120000);
		client.post(Config.URL_WS_VSMART, params, new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(int statusCode, Throwable error) {
				super.onFailure(statusCode, error);
				Log.i("DATA", error.toString());
			}

			@Override
			public void onSuccess(int statusCode, JSONObject re) {
				try {
					Log.i("DATA", re.toString());
					if (statusCode == 200){
						Log.i("DATA", "Tranfer thanh cong");
					} else {
						Log.i("DATA", "Tranfer thatbai");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
		});
	}
	
	void uploadImage(byte[] bbnt, byte[] bbbgtb) {
		
		RequestParams params = new RequestParams();
		params.put("userAssignId", String.valueOf(1));
		params.put("taskId", String.valueOf(1));
		params.put("BBNT", new ByteArrayInputStream(bbnt), "bbnt.jpg");
		params.put("BBBGTB", new ByteArrayInputStream(bbbgtb), "bbbgtb.jpg");

		AsyncHttpClient client = new AsyncHttpClient();
		client.post(HttpBasicClientHelper.BASE_URL , params,
			new MyJsonHttpResponseHandler() {

			    @Override
			    public void onFailure(Throwable error) {
				super.onFailure(error);
				Log.e("DATA", "Request failed", error);
				
			    }

			    @Override
			    public void onSuccess(JSONObject re) {
				
				try {
				    
				    Log.d("DATA", this.getClass().getSimpleName() + " Error" + re.toString());
				    
				    
				} catch (Exception e) {
				    e.printStackTrace();
				}
			    }
			});
	    }
	
	private byte[] convertFromFile(String source) {
		File f = new File(source);
		InputStream in = null;
		try {
			in = new FileInputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		byte[] buff = new byte[8000];

		int bytesRead = 0;

		ByteArrayOutputStream bao = new ByteArrayOutputStream();

		try {
			while ((bytesRead = in.read(buff)) != -1) {
			bao.write(buff, 0, bytesRead);
			}
			bao.flush();
			if (null != in)
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	}

		byte[] data = bao.toByteArray();

		Log.d("Tuan", this.getClass().getSimpleName() + " convertFromFile source:" + source + " data:" + data);

		// ByteArrayOutputStream stream = new ByteArrayOutputStream();
		// byteArray = stream.toByteArray();

		return data;
    }
	
	

	private void sendData(String path, String url){
		
		HttpClient httpclient = new DefaultHttpClient();
		String Url = url + "workMaintainController/onUpdateComplete";
		HttpPost httppost = new HttpPost(Url);
		try {
			MultipartEntity reqEntity = new MultipartEntity();
			int i = 0;
			FileBody bin = new FileBody(new File(path));
			StringBody comment = new StringBody("Upload Image");
			String partName = "fileup" + String.valueOf(i);
			reqEntity.addPart(partName, bin);
			// set gia tri update cong viec

			httppost.setEntity(reqEntity);
			httppost.addHeader("workingId", "1");
			
			httppost.addHeader("sid", "1");
			httppost.addHeader("userName", "duytv5");

			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost,
					responseHandler);
			Log.i("QLCTKT", "responseBody : " + responseBody);
			System.out.println("responseBody : " + responseBody);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

}*/